package com.quectel.mobile.controller.household;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.thirdconfig.ThirdPlatformConfigBusiness;
import com.quectel.constant.global.SMSConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.module.household.dto.HouseholdAuditDto;
import com.quectel.core.module.household.dto.HouseholdDto;
import com.quectel.core.module.household.dto.HouseholdRoomDto;
import com.quectel.core.module.household.service.HouseholdAuditService;
import com.quectel.core.module.household.service.HouseholdRoomService;
import com.quectel.core.module.household.service.HouseholdService;
import com.quectel.core.module.mobileuser.dto.MobileUserDto;
import com.quectel.core.module.village.dto.VillageRoomDto;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.mobile.controller.BaseController;
import com.quectel.mobile.interceptor.LoginMobileUserSession;
import com.quectel.mobile.util.SessionHolder;
import com.quectel.mobile.util.SmsCompnent;
import com.quectel.mobile.vo.household.AddMemberVo;
import com.quectel.mobile.vo.household.HouseholdReqVo;
import com.quectel.mobile.vo.mobileuser.login.SendVerCodeVo;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author rananxin
 * @date 2021-12-14 09:32:00
 */
@RestController
@RequestMapping("householdAudit")
@Tag(name = "HouseholdAuditController", description = "人员审核表相关api")
public class HouseholdAuditController extends BaseController {

    @DubboReference
    private HouseholdAuditService householdAuditService;
    @DubboReference
    private HouseholdRoomService householdRoomService;
    @DubboReference
    private HouseholdService householdService;
    @DubboReference
    private VillageRoomService villageRoomService;
    @Autowired
    private SmsCompnent smsCompnent;

    @Autowired
    private ThirdPlatformConfigBusiness thirdPlatformConfigBusiness;

    @GetMapping("auditList")
    @Operation(summary = "住户审核的分页查询列表")
    public Response<Page<HouseholdAuditDto>> list(
            @Parameter(description = "0初始化 1审核通过 2审核不通过") @RequestParam String auditStatus,
            @Parameter(description = "0初始化 1审核通过 2审核不通过") @RequestParam Long villageId,
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {

        MobileUserDto mobileUser = SessionHolder.getLoginMobileUserSession().getMobileUser();
        if (mobileUser == null) {
            return Response.error("完善基本信息");
        }

        Request request = Request.configParams(Request.parseParams(httpServletRequest))
                .put(LambdaUtil.getFieldName(HouseholdAuditDto::getApplyUserId), mobileUser.getId())
                .put(LambdaUtil.getFieldName(HouseholdAuditDto::getAuditStatus), auditStatus);

        int total = householdAuditService.queryTotal(request.getParams());

        List<HouseholdAuditDto> list = new ArrayList<>();
        if (total > 0) {
            list = householdAuditService.queryList(request.getParams());
        }

        Page<HouseholdAuditDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<HouseholdAuditDto>>ok().wrap(page);
    }

    /**
     * 发送验证码
     *
     * @return
     */
    @PostMapping("sendAddMemberMsgCode")
    @Operation(summary = "发送为他人认证验证码")
    public Response<Object> sendAddMemberMsgCode(@RequestBody SendVerCodeVo sendVerCodeVo) {

        SessionHolder.checkHousehold();

        LoginMobileUserSession loginMobileUserSession = SessionHolder.getLoginMobileUserSession();
        HouseholdDto currentHousehold = loginMobileUserSession.getCurrentHousehold();

        String code = smsCompnent.sendVerCode(currentHousehold.getTenantId(), sendVerCodeVo.getMobile(), SMSConstants.VerCodeType.ADD_MEMBER);
        if (code == null) {
            return Response.error("发送验证码失败");
        }

        return Response.ok().wrap(thirdPlatformConfigBusiness.smsMockEnable(currentHousehold.getTenantId()) ? code : null);
    }

    @PostMapping("addMember")
    @Operation(summary = "他人认证申请")
    public Response<Object> addMember(@RequestBody AddMemberVo addMemberVo) {
        SessionHolder.checkMobileUser();

        LoginMobileUserSession loginMobileUserSession = SessionHolder.getLoginMobileUserSession();
        MobileUserDto mobileUser = loginMobileUserSession.getMobileUser();

        HouseholdDto currentHousehold = SessionHolder.getLoginMobileUserSession().getCurrentHousehold();
        if (currentHousehold == null) {
            return Response.error("未认证为住户");
        }
        HouseholdRoomDto householdRoomDto = householdRoomService.selectByHouseholdIdAndRoomId(currentHousehold.getId(), addMemberVo.getRoomId());
        if (!HouseholdAuditDto.IdentityCategoryEnum.OWNER.getType().equals(householdRoomDto.getIdentityCategory())) {
            return Response.error("不是该房间的业主，不能为他人认证");
        }

        VillageRoomDto villageRoomDto = villageRoomService.selectById(addMemberVo.getRoomId());
        if (villageRoomDto == null) {
            Response.error("房间不存在");
        }

        // 为他人认证，手机号可以为空
        if (StringUtils.isNotBlank(addMemberVo.getMobile())) {
            boolean isLegal = smsCompnent.checkVerCode(addMemberVo.getMobile(), addMemberVo.getVerCode(), SMSConstants.VerCodeType.ADD_MEMBER);
            if (!isLegal) {
                return Response.error("您输入验证码不正确或者不在有效期内");
            }

            /*判断添加成员是否已经拥有该房间*/
            HouseholdDto memberHousehold = householdService.selectByVillageIdAndMobile(villageRoomDto.getVillageId(), addMemberVo.getMobile());
            if (memberHousehold != null) {
                HouseholdRoomDto memberHouseholdRoom = householdRoomService.selectByHouseholdIdAndRoomId(memberHousehold.getId(), villageRoomDto.getId());
                if (memberHouseholdRoom != null) {
                    return Response.error("您所添加的人员在该房间已存在");
                }
            }

            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put(LambdaUtil.getFieldName(HouseholdAuditDto::getMobile), addMemberVo.getMobile());
            queryParams.put(LambdaUtil.getFieldName(HouseholdAuditDto::getRoomId), addMemberVo.getRoomId());
            queryParams.put(LambdaUtil.getFieldName(HouseholdAuditDto::getAuditStatus), SystemConstants.NO);
            List<HouseholdAuditDto> initAuditList = householdAuditService.queryList(queryParams);
            if (initAuditList != null && initAuditList.size() > 0) {
                return Response.error("请耐心等待上次提交审核结果");
            }

        }


        Date date = new Date();

        HouseholdAuditDto householdAuditDto = CopyUtils.copyObj(addMemberVo, HouseholdAuditDto.class);
        householdAuditDto.setTenantId(villageRoomDto.getTenantId());
        householdAuditDto.setSource(HouseholdAuditDto.SourceEnum.HOUSEHOLD_AUDIT.getType());
        householdAuditDto.setApplyUserId(mobileUser.getId());
        householdAuditDto.setAuditStatus(SystemConstants.NO);
        householdAuditDto.setVillageId(villageRoomDto.getVillageId());
        householdAuditDto.setCreateTime(date);
        householdAuditService.save(householdAuditDto);
        return Response.ok();
    }

    @PostMapping("householdReq")
    @Operation(summary = "业主认证申请")
    public Response<Object> householdReq(@RequestBody @Validated HouseholdReqVo householdReqVo) {
        SessionHolder.checkMobileUser();

        LoginMobileUserSession loginMobileUserSession = SessionHolder.getLoginMobileUserSession();
        MobileUserDto mobileUser = loginMobileUserSession.getMobileUser();

        VillageRoomDto villageRoomDto = villageRoomService.selectById(householdReqVo.getRoomId());
        if (villageRoomDto == null) {
            Response.error("房间不存在");
        }
        HouseholdDto householdDto = householdService.selectByVillageIdAndMobile(villageRoomDto.getVillageId(), mobileUser.getMobile());
        if (householdDto != null) {
            HouseholdRoomDto householdRoomDto = householdRoomService.selectByHouseholdIdAndRoomId(householdDto.getId(), villageRoomDto.getId());
            if (householdRoomDto != null) {
                return Response.error("您已经拥有该房间");
            }
        }

        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put(LambdaUtil.getFieldName(HouseholdAuditDto::getMobile), mobileUser.getMobile());
        queryParams.put(LambdaUtil.getFieldName(HouseholdAuditDto::getRoomId), householdReqVo.getRoomId());
        queryParams.put(LambdaUtil.getFieldName(HouseholdAuditDto::getAuditStatus), SystemConstants.NO);
        List<HouseholdAuditDto> initAuditList = householdAuditService.queryList(queryParams);

        if (initAuditList != null && initAuditList.size() > 0) {
            return Response.error("请耐心等待上次提交审核结果");
        }
        Date date = new Date();

        HouseholdAuditDto householdAuditDto = CopyUtils.copyObj(householdReqVo, HouseholdAuditDto.class);
        householdAuditDto.setTenantId(villageRoomDto.getTenantId());
        householdAuditDto.setSource(HouseholdAuditDto.SourceEnum.HOUSEHOLD_AUDIT.getType());
        householdAuditDto.setApplyUserId(mobileUser.getId());
        householdAuditDto.setAuditStatus(SystemConstants.NO);
        householdAuditDto.setVillageId(villageRoomDto.getVillageId());

        householdAuditDto.setMobile(householdReqVo.getMobile());
        householdAuditDto.setGender(householdReqVo.getGender());
        householdAuditDto.setName(householdReqVo.getName());

        householdAuditDto.setCreateTime(date);
        householdAuditService.save(householdAuditDto);
        return Response.ok();
    }
}
